package com.woniu.zsd.recycle.xxl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.zsd.recycle.dto.RecycleDtatistics;
import com.woniu.zsd.recycle.service.RecyclingOrderService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
public class RecycleSale {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RecyclingOrderService recyclingOrderService;

    //每天统计废品的销售数据
    @XxlJob("RecycleSaleDay")
    public void recycleSale(String param) throws Exception {
        Integer stationId = Integer.parseInt(param);
        // 获取今天的日期
        LocalDate today = LocalDate.now();

        // 获取今天的开始时间：00:00:00
        LocalDateTime startOfDay = today.atStartOfDay();

        // 获取今天的结束时间：23:59:59
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX);

        List<RecycleDtatistics> dtos = recyclingOrderService.select(startOfDay, endOfDay);
        // 将统计结果保存到redis中
        // 创建 ObjectMapper 实例,导入的是jackson的包
        ObjectMapper objectMapper = new ObjectMapper();
        // 将 ProductStatisticsDto 对象转换为 JSON 字符串
        String jsonString = objectMapper.writeValueAsString(dtos);
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 设置日期格式化样式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 格式化当前日期
        String formattedDate = currentDate.format(formatter);
        String key = formattedDate+"_RecycleSaleDay";
        stringRedisTemplate.opsForValue().set(key, jsonString);
    }
}
